﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Handrise.BasicModal.Serialization;
using System.Xml;

namespace Handrise.CDCable.Business
{
    /// <summary>
    /// 指挥信息服务
    /// </summary>
    public class CommunicationService
    {
        private ServerExchange serverExchange = new ServerExchange();

        /// <summary>
        /// 上传指挥信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="communicationsBuffer">指挥信息实体列序列化流</param>
        /// <returns></returns>
        public bool UploadCommunication(string userName, byte[] communicationsBuffer)
        {
            CompactFormatterPlus cfp = new CompactFormatterPlus();
            List<Communication> communications = (List<Communication>)cfp.Deserialize(communicationsBuffer);

            string entitysXML = CommonFunction.GetXMLFromEnitys<Communication>(communications, typeof(Communication));

            string receiveData = serverExchange.UploadCommunication(userName, entitysXML);

            return CommonFunction.ReturnDataIsOk(receiveData); ;
        }

        /// <summary>
        /// 下载指挥信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="communicationsBuffer"></param>
        /// <returns></returns>
        public bool DownloadCommunication(string userName, out byte[] communicationsBuffer)
        {
            communicationsBuffer = null;

            string receiveData = serverExchange.DownloadCommunication(userName);

            //处理数据
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(receiveData);
            //先尝试获取正确的返回结果
            XmlNode xnValue = CommonFunction.GetXmlNode(xmlDoc, "message/operation/returnValue/value");
            if (xnValue == null)
            {
                //没有正确的返回结果
                return false;
            }

            //分析返回的内容
            XmlDocument userInfoXmlDoc = new XmlDocument();
            userInfoXmlDoc.LoadXml(xnValue.InnerText);
            XmlNode xnEnitys = CommonFunction.GetXmlNode(userInfoXmlDoc, "com.techstar.pda.support.Pdacommunications");
            if (xnEnitys == null)
                return false;

            CompactFormatterPlus cfp = new CompactFormatterPlus();

            //指挥信息
            List<Object> communications = CommonFunction.GetEntitysFromXML(xnEnitys, typeof(Communication));

            //设置指挥信息数据
            foreach (Communication communication in communications)
            {
                communication.RecordDateTime = DateTime.Now;
            }
            communicationsBuffer = cfp.Serialize(communications);

            return true;
        }
    }
}
